package org.example.cet.demos.controller;

import io.jsonwebtoken.Claims;
import org.example.cet.demos.domain.po.User;
import org.example.cet.demos.service.impl.UserLoginServiceImpl;
import org.example.cet.demos.service.impl.UserServiceImpl;
import org.example.cet.demos.exception.CommonException;
import org.example.cet.demos.domain.Result;
import org.example.cet.demos.service.UserService;
import org.example.cet.demos.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 *目录名
 *
 */
@RestController
public class UserLoginController {
    @Autowired
    private UserLoginServiceImpl userService;

    /**
     *
     * 接口名
     * @param user
     * @return
     */
    @PostMapping("/login")
    public Result login(@RequestBody User user) {
        User u = userService.login(user);
        String username = user.getUsername();
        String password = user.getPassword();
        if (username == "" || password=="") {
            throw new CommonException("用户名或密码为空");
        }
        //登陆成功
        if (u != null) {
            Map<String, Object> claims = new HashMap<>();
//            claims.put("id", u.getId());
//            claims.put("name", u.getName());
            claims.put("username", u.getUsername());
            String jwt = JwtUtils.generateJwt(claims);
//            return Result.success("登陆成功",jwt);
            try {
                Claims parsedClaims = JwtUtils.parseJwt(jwt);
                Map<String, String> map = new LinkedHashMap<>();
                map.put("id", String.valueOf(u.getId()));
                map.put("username", u.getUsername());
                map.put("password", u.getPassword());
                map.put("gender",u.getGender());
                map.put("role", u.getRole());
                map.put("tel", u.getTel());
                map.put("token", jwt);
                return Result.success("登录成功",map);
            } catch (Exception e) {
                return Result.error(0, "JWT 验证失败");
            }
        }
        //登录失败
        return Result.error(0, "用户名或密码错误");
    }
}
